const path = require('path');
const { format, transports } = require("winston");
const { combine, timestamp, json } = format;
require('winston-daily-rotate-file');

let LOGGER_CONF;

if (process.env.NODE_ENV !== 'production') {
  LOGGER_CONF = {
    transports: [new transports.Console()]
  };
} else {
  LOGGER_CONF = {
    defaultMeta: { service: 'todolist-service' },
    transports: [
      new transports.DailyRotateFile({
        level: 'info',
        filename: path.resolve(__dirname, '../logs', 'info', '%DATE%.log'),
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        format: combine(
          timestamp(),
          format((info) => {
            const reqLog = Object.assign({}, {
              url: info.url,
              method: info.method,
            }, info.request.headers);
            (reqLog.cookie) && (reqLog.cookie = '******');
            (reqLog.token) && (reqLog.token = '******');
            const resLog = Object.assign({}, {
              status: info.status,
              message: info.message
            }, info.response.headers);
            return {
              level: info.level,
              message: info.message,
              service: info.service,
              timestamp: info.timestamp,
              reqLog,
              resLog
            };
          })(),
          json()
        )
      }),
      new transports.DailyRotateFile({
        level: 'error',
        filename: path.resolve(__dirname, '../logs', 'error', '%DATE%.log'),
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        format: combine(
          timestamp(),
          format((info) => {
            return Object.assign(info.errorMsg, { timestamp: info.timestamp });
          })(),
          json()
        )
      })
    ]
  };
}

module.exports = LOGGER_CONF;
